#!/bin/sh

package="$1"
[ -f "$package" ] || {
	echo "No such file: $package" >&2
	exit 1
}

name="`basename "$package"`"
name="${name%.*}"

[ -d /dev/shm ] && [ -w /dev/shm ] && tmp=/dev/shm || tmp=/tmp
tmp="`mktemp -d "$tmp"/zn-expand.XXXXXX`"
[ -d "$tmp" ] || {
	echo "Failed to create a temporary directory: $tmp" >&2
	exit 1
}


origDir="`pwd`"
expandDir="$tmp/$name"
mkdir "$expandDir"
unzip "$package" -d "$expandDir"
cd "$expandDir"

which json_xs && {
	find . -type f -name '*.json' -exec sh -c 'json_xs -t json-pretty < "$1" > "$1.tmp" && mv "$1.tmp" "$1"' -- {} \;
:;} || which json_prettify && {
	find . -type f -name '*.json' -exec sh -c 'json_prettify < "$1" > "$1.tmp" && mv "$1.tmp" "$1"' -- {} \;
:;} || {
	echo "No JSON supported" >&2
	exit 1
}

find . -type f -name '*.html' -exec sh -c 'sed "s/</\n</g" < "$1" > "$1.tmp" && mv "$1.tmp" "$1"' -- {} \;

cd ..
expandedName="$name.expanded.tar.lz"
tar -c * | lzip -9 > "$expandedName"

cd "$origDir"
mv -v "$tmp/$expandedName" ./
rm -fr "$tmp"
echo "Done!" >&2

# vim: ts=4 noet ai

